package com.core.common.exception;

import com.core.common.domain.response.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.*;

import java.sql.SQLIntegrityConstraintViolationException;


@Slf4j
@RestControllerAdvice(annotations = Controller.class)
public class GlobalExceptionHandler {


    @ExceptionHandler(value = {MethodArgumentNotValidException.class})
    public R defaultErrorHandler(MethodArgumentNotValidException e) throws Exception {
        String errorMesssage = "";
        BindingResult bindingResult = e.getBindingResult();
        if(bindingResult != null && !CollectionUtils.isEmpty(bindingResult.getFieldErrors())){
            for (FieldError fieldError : bindingResult.getFieldErrors()) {
                errorMesssage =errorMesssage+fieldError.getField()+ fieldError.getDefaultMessage() + ",";
            }
            errorMesssage="参数校验异常:"+errorMesssage.substring(0,errorMesssage.length()-1);
        }
        return  R.error(400010,errorMesssage);
    }


    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)//处理的异常！
    public R exceptionHandler(SQLIntegrityConstraintViolationException ex){
        log.error(ex.getMessage());//异常信息,日志通过日志看到后面的异常中需要的异常重复账号的字段
        //如果这sql异常信息有Duplicate entry字段,就进一步说明是账号重复的异常
        if(ex.getMessage().contains("Duplicate entry")){
            String[] split = ex.getMessage().split(" ");//这个异常信息里面有重复的账号,拿到它！
            String msg = split[2] + "已存在";//进行拼接
            return R.error(msg);//进行返回
        }
        return R.error("未知错误");
    }



    @ExceptionHandler(value = Exception.class)
    public R handle(Exception e) {
        e.printStackTrace();
        return  R.error(400010,e.getMessage());
    }


}